import React, { Component } from 'react';
import { Popover, Input } from 'antd';
import { clearNoNum, formatMoney } from '/common/utils/numberUtils';

class MoneyInput extends Component {
  // 返回一个对象来更新 state
  static getDerivedStateFromProps(nextProps) {
    // Should be a controlled component.
    if ('value' in nextProps) {
      return {
        value: nextProps.value,
      };
    }
    return null;
  }

  constructor(props) {
    super(props);
    this.state = {
      value: props.value || null,
      showPop: false,
    };
  }

  handleChange(e) {
    const value = e.currentTarget.value;
    let val;
    if (isNaN(value)) {
      if ('-' === value) {
        val = value;
      } else {
        val = isNaN(parseFloat(value)) ? null : `${parseFloat(value)}`;
      }
    } else if (value >= 1000000000 || value <= -1000000000) {
      val = `${this.state.value}`;
    } else {
      val = clearNoNum(value);
      if (value < 0) {
        val = `${0 - val}`;
      }
    }

    if (!('value' in this.props)) {
      this.setState({ value: val });
    }
    this.triggerChange(val);
    this.setState({ showPop: true });
  }

  triggerChange = (changedValue) => {
    // Should provide an event to pass value to Form.
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(changedValue);
    }
  };

  handleBlur() {
    this.setState({ showPop: false }, () => {
      const { nativeProps } = this.props;
      if (nativeProps && nativeProps.onBlur) {
        nativeProps.onBlur();
      }
    });
  }

  render() {
    const { nativeProps, popoverProps = {} } = this.props;
    return (
        <div className={'money-input-wrap'}>

          <Popover placement="top"
                   overlayClassName={'money-input-wrap'}
                   content={
                     <div className={'m-show-panel'}>
                       <span className="m-number">{formatMoney(this.state.value || 0)}</span>
                     </div>
                   } visible={this.state.showPop} {...popoverProps}>
            <Input
                {...nativeProps}
                value={this.state.value}
                onChange={this.handleChange.bind(this)}
                onBlur={this.handleBlur.bind(this)}
            />
          </Popover>
        </div>
    );
  }
}

export default MoneyInput;

